package com.ylbh.modules.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.pojo.activity.dto.ActivityTemplateDTO;
import com.ylbh.common.pojo.activity.dto.ShoppingActivityDTO;
import com.ylbh.common.pojo.activity.dto.WholePointActivitiesDTO;
import com.ylbh.common.pojo.activity.vo.ShoppingActivityVO;
import com.ylbh.common.pojo.activity.vo.WholePointActivitiesTimeVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.activity.mapper.SpikeActivityMapper;
import com.ylbh.modules.activity.service.SpikeActivityService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author mgh
 */
@Service("spikeActivityService")
public class SpikeActivityServiceImpl extends ServiceImpl<SpikeActivityMapper, ShoppingActivityDTO> implements SpikeActivityService {
    @Autowired
    private SpikeActivityMapper spikeActivityMapper;
    @Autowired
    RedisUtils redisUtils;

    /**
     * 获取活动列表
     * @param params
     * @return
     */
    @Override
    public PageUtils queryActivityPage(PageDTO params) {
        QueryWrapper<ShoppingActivityDTO> shoppingActivityDTOQueryWrapper = new QueryWrapper<>();
        shoppingActivityDTOQueryWrapper.eq("delete_status",1);

        shoppingActivityDTOQueryWrapper.orderByDesc("update_time");

        String title =params.getKeywords();

        if(StringUtils.isNotBlank(title)){
            shoppingActivityDTOQueryWrapper.eq("activity_title",title);
        }
        return new PageUtils(spikeActivityMapper.selectList(shoppingActivityDTOQueryWrapper),
                spikeActivityMapper.selectCount(shoppingActivityDTOQueryWrapper),
                params.getLimit(),
                params.getPage());
    }

    /**
     * 获取活动名列表
     * @return
     */
    @Override
    public List<ShoppingActivityVO> queryActivityNameList() {

        return spikeActivityMapper.selectActivityNameList();
    }

    /**
     * 更新活动上下架状态
     */
    @Override
    public void updateState() {
        redisUtils.deleteKeys("querySeckillGoodsInfoByPage*");
        redisUtils.deleteKeys("com.yilianbaihui.shopping.seckill*");
        Date date = DateUtils.todayWholePoint(new Date());
        // 更新活动状态
        spikeActivityMapper.openActivity(date);
        spikeActivityMapper.closeActivity(date);

        // 更新商品状态
        spikeActivityMapper.openActivityGood(date);
        spikeActivityMapper.closeActivityGood(date);
    }

    /**
     * 添加整点抢购时间
     * @param wholePointActivitiesDTO
     * @return
     */
    @Override
    public void addWholePointActivities(WholePointActivitiesDTO wholePointActivitiesDTO) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 先根据活动id去查询活动的区间
        ShoppingActivityDTO dates = spikeActivityMapper.selectShoppingActivityTime(wholePointActivitiesDTO.getActivityId());
        List<Date> date = findDates(dates.getBeginTime(), dates.getEndTime());
        wholePointActivitiesDTO.setCreateUserId(ShiroUtils.getUserId().intValue());
        wholePointActivitiesDTO.setCreateTime(new Date());
        IdWorker idWorker = new IdWorker();
        for (int i = 0; i < date.size(); i++) {
            wholePointActivitiesDTO.setId(idWorker.nextId());
            wholePointActivitiesDTO.setActiviteTime(sdf.format(date.get(i)) + " 00:00:00");
            wholePointActivitiesDTO.setActivityStartTime(sdf.format(date.get(i)) + " " + wholePointActivitiesDTO.getStartTime() + ":00");
            wholePointActivitiesDTO.setActivityEndTime(sdf.format(date.get(i)) + " " + wholePointActivitiesDTO.getEndTime() + ":00");
            spikeActivityMapper.insertWholePointActivities(wholePointActivitiesDTO);
        }
    }

    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime()))
        {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    /**
     * 获取整点时间列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils getWholePointActivitiesTime(PageDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<WholePointActivitiesTimeVO> list = spikeActivityMapper.selectWholePointActivitiesTime(pageDTO.getKeywords(), page);
        return new PageUtils(new Page<WholePointActivitiesTimeVO>().setRecords(list).setTotal(page.getTotal()));
    }

    /**
     * 添加整点抢购模板
     * @param activityTemplateDTO
     */
    @Override
    public void addActivityTemplate(ActivityTemplateDTO activityTemplateDTO) {
        activityTemplateDTO.setId(new IdWorker().nextId());
        activityTemplateDTO.setCreateTime(new Date());
        activityTemplateDTO.setCreateUserId(ShiroUtils.getUserId().intValue());
        spikeActivityMapper.insertActivityTemplate(activityTemplateDTO);
    }

    /**
     * 获取对应抢购的模板详情
     * @param id
     * @return
     */
    @Override
    public ActivityTemplateDTO getActivityTemplateDetails(String id) {
        return spikeActivityMapper.selectActivityTemplateDetails(id);
    }

    /**
     * 整点抢购模板列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils queryActivityTemplateList(PageDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<ActivityTemplateDTO> list = spikeActivityMapper.selectActivityTemplateList(page);
        return new PageUtils(new Page<ActivityTemplateDTO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 修改整点抢购模板
     * @param activityTemplateDTO
     */
    @Override
    public void modifyActivityTemplateById(ActivityTemplateDTO activityTemplateDTO) {
        activityTemplateDTO.setCreateUserId(ShiroUtils.getUserId().intValue());
        activityTemplateDTO.setCreateTime(new Date());
        spikeActivityMapper.updateActivityTemplateById(activityTemplateDTO);
    }

    /**
     * 删除整点抢购
     * @param ids
     */
    @Override
    public void removeActivityTemplate(List<String> ids) {
        spikeActivityMapper.updateActivityTemplateByIds(ids);
    }

    /**
     * 插入活动地址记录
     * @param address
     */
    @Override
    public void addActivityAddress(String address, String activityId) {
        if (!StringUtils.isEmpty(address)) {
            String[] names = address.split(",");
            IdWorker idWorker = new IdWorker();
            for (int i = 0; i < names.length; i++) {
                spikeActivityMapper.insertActivityAddress(idWorker.nextId(), names[i], activityId, ShiroUtils.getUserId(), new Date());
            }
        }
    }

    /**
     * 判断活动的时间区间天数
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<String> getActivityTimeDays(String startTime, String endTime) {
        List<String> list = new ArrayList<>();
        String[] dateBegs = startTime.split("-");
        String[] dateEnds = endTime.split("-");
        Calendar start = Calendar.getInstance();
        start.set(Integer.valueOf(dateBegs[0]), Integer.valueOf(dateBegs[1]) - 1, Integer.valueOf(dateBegs[2]));
        Long startTIme = start.getTimeInMillis();
        Calendar end = Calendar.getInstance();
        end.set(Integer.valueOf(dateEnds[0]), Integer.valueOf(dateEnds[1]) - 1, Integer.valueOf(dateEnds[2]));
        Long endTimes = end.getTimeInMillis();
        Long oneDay = 1000 * 60 * 60 * 24l;
        Long time = startTIme;
        while (time <= endTimes) {
            Date d = new Date(time);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            time += oneDay;
            list.add(df.format(d));
        }
        return list;
    }

    /**
     * 替换整点限时抢购时间
     * @param updateTime
     * @param originalTime
     * @param activityId
     */
    @Override
    public void modifyWholePoint(List<String> updateTime, List<String> originalTime, String activityId) {
        // 根据活动id查询出所有的整点场次
        List<WholePointActivitiesTimeVO> list = spikeActivityMapper.selectWholePointByActivityId(activityId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        int num = list.size() / updateTime.size();
//        int count = 0;
//        for (int i = 0; i < updateTime.size(); i++) {
//            String[] originalActivityTime = sdf.format(list.get(i).getActiviteTime()).split(" ");
//            String[] originalBeginTime = sdf.format(list.get(i).getBeginTime()).split(" ");
//            String[] originalEndTime = sdf.format(list.get(i).getEndTime()).split(" ");
//            spikeActivityMapper.updateWholePointActivityById(updateTime.get(i) + " " + originalActivityTime[1], updateTime.get(i) + " " + originalBeginTime[1], updateTime.get(i) + " " + originalEndTime[1], new Date(), ShiroUtils.getUserId(), list.get(count).getId());
////            if (originalActivityTime.length == 2 && originalBeginTime.length == 2 && originalEndTime.length == 2) {
////                // 根据id修改整点场次
////                for (int j = 0; j < num; j++) {
////                    spikeActivityMapper.updateWholePointActivityById(updateTime.get(i) + " " + originalActivityTime[1], updateTime.get(i) + " " + originalBeginTime[1], updateTime.get(i) + " " + originalEndTime[1], new Date(), ShiroUtils.getUserId(), list.get(count).getId());
////                    count = count + 1;
////                }
////            }
//        }

        if (list.size() > 1) {
            // 根据活动结束时间来倒序
            list.sort((a1, a2) -> {
                try {
                    return sdf.parse(sdf.format(a1.getBeginTime())).compareTo(sdf.parse(sdf.format(a2.getBeginTime())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 1;
            });
        }

        // 根据整点的长度/修改时间长度=每天的场次
        int num = list.size() / updateTime.size();
        int count = 0;
        for (int i = 0; i < updateTime.size(); i++) {
            for (int j = 0; j < num; j++) {
                String[] originalActivityTime = sdf.format(list.get(count).getActiviteTime()).split(" ");
                String[] originalBeginTime = sdf.format(list.get(count).getBeginTime()).split(" ");
                String[] originalEndTime = sdf.format(list.get(count).getEndTime()).split(" ");
                // 修改id
                String newId = new IdWorker().nextId();
                spikeActivityMapper.updateWholePointActivityById(updateTime.get(i) + " " + originalActivityTime[1], updateTime.get(i) + " " + originalBeginTime[1], updateTime.get(i) + " " + originalEndTime[1], new Date(), ShiroUtils.getUserId(), list.get(count).getId(), newId);
                // 将原id下的商品全部替换成新的活动整点id
                spikeActivityMapper.updateActivityGoodsIdByOldId(list.get(count).getId(), newId);
                count = count + 1;
            }

        }
    }

    /**
     * 修改整点和商品上下线状态
     * @param state
     */
    @Override
    public void modifyActivityGoodsByStateType(Integer state, String activityId) {
        // 表示要将活动上线
        // 1.先查询出活动整点的id
        List<String> list = spikeActivityMapper.selectActivityTimeId(activityId);
        int type = 2;
        if (state == 1) {
            type = 1;
        } else {
            type = 0;
        }
        if (type == 0 || type == 1) {
            // 先修改活动商品为上线状态
            // 2.去活动商品中修改商品状态
            spikeActivityMapper.updateActivityGoodsById(list, type);
            // 再修改整点抢购时间状态
            spikeActivityMapper.updatePointActivitiesByActivityId(activityId, type);
            // 最后修改大活动状态
            spikeActivityMapper.updateShoppingActivityByActivityId(activityId, type);
        }
    }
}
